import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'root',
    redirect: to => {
      const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true' && localStorage.getItem('token')
      return isLoggedIn ? '/data-analytics' : '/login'
    }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/LoginView.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/HomeView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('@/views/AboutView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/plugin-manager',
    name: 'plugin-manager',
    component: () => import('@/views/PluginManagerView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/dashboard',
    name: 'dashboard',
    component: () => import('@/views/HomeView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/data-analytics',
    name: 'data-analytics',
    component: () => import('@/views/DataAnalyticsView.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true' && token
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)

  // 如果已登录且访问的是登录页，重定向到数据统计页
  if (isLoggedIn && to.path === '/login') {
    next({ path: '/data-analytics' })
  } 
  // 如果需要认证但未登录，重定向到登录页
  else if (requiresAuth && !isLoggedIn) {
    next({ path: '/login' })
  } 
  // 其他情况正常导航
  else {
    next()
  }
})

export default router 